/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ingenic.glass.camera;

import com.ingenic.glass.camera.CameraAppImpl;
import com.ingenic.glass.camera.util.Util;
import android.content.Context;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.location.Location;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.ImageColumns;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Storage {
    private static final String TAG = "CameraStorage";
    public static final String DCIM =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString();

      //public static final String DIRECTORY = DCIM + "/Camera";
    private static final int BASE_DIR_ID = R.string.base_storage_path;
    private static final int DIRECTORY_PICTURE_ID = R.string.picture_path;
    private static final int DIRECTORY_VIDEO_ID = R.string.video_path;
    private static final int DIRECTORY_VIDEO_THUMBNAILS_ID = R.string.video_thumbnails_path;

    public static String BASE_DIR = "";
    public static String DIRECTORY_PICTURE = "";
    public static String DIRECTORY_VIDEO = "";
    public static String DIRECTORY_VIDEO_THUMBNAILS = "";
    // Match the code in MediaProvider.computeBucketValues().
    public static String BUCKET_ID = "";

    public static void initialize(Context context) {
	    BASE_DIR = context.getString(BASE_DIR_ID);
	    DIRECTORY_PICTURE = context.getString(DIRECTORY_PICTURE_ID);
	    DIRECTORY_VIDEO = context.getString(DIRECTORY_VIDEO_ID);
	    DIRECTORY_VIDEO_THUMBNAILS = context.getString(DIRECTORY_VIDEO_THUMBNAILS_ID);
	    BUCKET_ID = String.valueOf(DIRECTORY_PICTURE.toLowerCase().hashCode());
    }

    public static String generate_QuickPicturefullname() {
	long dateTaken = System.currentTimeMillis();
        String title = Util.createJpegName(dateTaken);
        File dir = new File(DIRECTORY_PICTURE);
        if(!dir.exists()) {
        	dir.mkdirs();
        	try {
				Runtime.getRuntime().exec("chmod 777 " + dir.getAbsolutePath());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }

        String path = DIRECTORY_PICTURE + '/' + title + ".jpg";
	return path;
    }

    public static Uri addImage(ContentResolver resolver, String title, long date,
                Location location, int orientation, byte[] jpeg, int width, int height) {
        // Save the image.

	//create path /sdcard/IGlass/Pictures when it is not exist
        File dir = new File(DIRECTORY_PICTURE);
        if(!dir.exists())
        	dir.mkdirs();

        String path = DIRECTORY_PICTURE + '/' + title + ".jpg";
        FileOutputStream out = null;
        try {
		if (CameraAppImpl.IS_CRUISE_BOARD) {
			File outFile = new File(path);
			Log.d(TAG, outFile.getAbsolutePath());
			if(!outFile.exists()) {
				outFile.createNewFile();
				outFile.setExecutable(true, false);
				outFile.setReadable(true, false);
				outFile.setWritable(true, false);
			}
			out = new FileOutputStream(outFile);
		} else {
			out = new FileOutputStream(path);
		}
		out.write(jpeg);
        } catch (Exception e) {
            Log.e(TAG, "Failed to write image", e);
            return null;
        } finally {
            try {
                out.close();
            } catch (Exception e) {
            }
        }

        // Insert into MediaStore.
        ContentValues values = new ContentValues(9);
        values.put(ImageColumns.TITLE, title);
        values.put(ImageColumns.DISPLAY_NAME, title + ".jpg");
        values.put(ImageColumns.DATE_TAKEN, date);
        values.put(ImageColumns.MIME_TYPE, "image/jpeg");
        values.put(ImageColumns.ORIENTATION, orientation);
        values.put(ImageColumns.DATA, path);
        values.put(ImageColumns.SIZE, jpeg.length);
        values.put(ImageColumns.WIDTH, width);
        values.put(ImageColumns.HEIGHT, height);

        if (location != null) {
            values.put(ImageColumns.LATITUDE, location.getLatitude());
            values.put(ImageColumns.LONGITUDE, location.getLongitude());
        }

        Uri uri = resolver.insert(Images.Media.EXTERNAL_CONTENT_URI, values);
        if (uri == null) {
            Log.e(TAG, "Failed to write MediaStore");
            return null;
        }
        return uri;
    }

    /**
     * OSX requires plugged-in USB storage to have path /DCIM/NNNAAAAA to be
     * imported. This is a temporary fix for bug#1655552.
     */
    public static void ensureOSXCompatible() {
        File nnnAAAAA = new File(DCIM, "100ANDRO");
        if (!(nnnAAAAA.exists() || nnnAAAAA.mkdirs())) {
            Log.e(TAG, "Failed to create " + nnnAAAAA.getPath());
        }
    }
}